from django import forms
from web import models
from web.forms.bootstrap import BootstrapForm
from django.core.exceptions import ValidationError
from web.forms.widgets import ColorRadioSelect
class ProjectModelForm(BootstrapForm,forms.ModelForm):
    #方法一
    # desc=forms.CharField(widget=forms.Textarea(attrs={'class':'form-control',}),label='项目描述')
    bootstrap_class_exclude=['color',]
    def __init__(self,request,*args,**kwargs):
        super().__init__(*args,**kwargs)
        self.request=request

    class Meta:
        model=models.Project
        fields=['name','color','desc']
        #方法二
        widgets={
            # 'desc':forms.Textarea(attrs={'class':'form-control',}),
            'desc':forms.Textarea,
            'color':ColorRadioSelect(attrs={'class':'color-radio'}),
        }

    def clean_name(self):
        #1 检查项目名是否存在
        #2 检查用户是否有足够的权限创建项目

        name=self.cleaned_data.get('name')
        exists=models.Project.objects.filter(name=name,creator=self.request.tracer.user).exists()
        if exists:
            raise ValidationError('该项目已经存在')

        count=models.Project.objects.filter(creator=self.request.tracer.user).count()
        # self.request.tracer.price_policy.project_num
        print(count)
        print(self.request.tracer.price_policy.project_num)
        if self.request.tracer.price_policy.project_num<=count:
            raise ValidationError('项目个数超限，请购买套餐')
        return name